#include "board.h"

/**
  * @brief  配置TIM1复用输出PWM时用到的I/O
  * @param  无
  * @retval 无
  */
static void TIM1_GPIO_Config(void)
{
    rcu_periph_clock_enable(FAN_GPIO_CLK);
    gpio_mode_set(FAN_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, FAN_GPIO_PIN);
    gpio_output_options_set(FAN_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ,FAN_GPIO_PIN);
    gpio_af_set(FAN_GPIO_PORT, TIM1_CH2_AF, FAN_GPIO_PIN);
}

/**
  * @brief  配置TIM1在输出PWM情况下的工作模式
  * @param  无
  * @retval 无
  */
static void TIM1_PWMOUTPUT_Config(void)
{
    /* TIMER1 configuration: generate PWM signals with different duty cycles:
       SystemCoreClock=84000000
       TIMER16CLK = SystemCoreClock / 84 = 1MHz */
    timer_oc_parameter_struct timer_ocintpara;
    timer_parameter_struct timer_initpara;

    rcu_periph_clock_enable(FAN_TIM_CLK);
    timer_deinit(FAN_TIM);

    /* TIMER2 configuration */
    timer_initpara.prescaler         = (84-1);
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = 20000;  //20ms的周期
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(FAN_TIM,&timer_initpara);

     /* CH0 configuration in PWM mode */
    timer_ocintpara.outputstate  = TIMER_CCX_ENABLE;
    timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
    timer_ocintpara.ocpolarity   = TIMER_OC_POLARITY_HIGH;
    timer_ocintpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
    timer_ocintpara.ocidlestate  = TIMER_OC_IDLE_STATE_LOW;
    timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
    timer_channel_output_config(FAN_TIM,TIMER_CH_2,&timer_ocintpara);

    timer_channel_output_pulse_value_config(FAN_TIM,TIMER_CH_2,0);
    timer_channel_output_mode_config(FAN_TIM,TIMER_CH_2,TIMER_OC_MODE_PWM0);
    timer_channel_output_shadow_config(FAN_TIM,TIMER_CH_2,TIMER_OC_SHADOW_DISABLE);

    timer_primary_output_config(FAN_TIM,ENABLE);
    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(FAN_TIM);
    timer_enable(FAN_TIM);
}

  // 失能定时器

/**
  * @brief  初始化通用控制定时器定时
  * @param  无
  * @retval 无
  */
void TIM1_Fan_Configuration(void)
{
  TIM1_GPIO_Config();
  TIM1_PWMOUTPUT_Config();
}

/**
  * @brief  控制蜂鸣器的开关
  * @param  level:风机档位
  *         0:关闭
  *         1:小档位
  *         2:全开
  * @retval 无
  */
void FanControl(uint8_t level)
{
  switch (level)
  {
  case 0:timer_channel_output_pulse_value_config(FAN_TIM,TIMER_CH_2,0);break;
  case 1:timer_channel_output_pulse_value_config(FAN_TIM,TIMER_CH_2,4000);break;     //这里将PWM改为200不知如何
  case 2:timer_channel_output_pulse_value_config(FAN_TIM,TIMER_CH_2,20000);break;
  default:timer_channel_output_pulse_value_config(FAN_TIM,TIMER_CH_2,0);break;
  }
}